//
//  HYAudioSuspensionView.m
//  VPlayer
//
//  Created by liguoqing on 2023/9/22.
//

#import "HYAudioSuspensionView.h"
#import "HYAudioRoomViewController.h"
#import "UIImageView+PlayGIF.h"

#define Border_Gap          4
#define End_Play_Loc_Key    [NSString stringWithFormat:@"audio_%@_move_key", self.class]

@interface HYAudioSuspensionView ()

@property (nonatomic, strong) HYAudioRoomViewController *audioRoomPlayer;

@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) UIView *cView;

@property (nonatomic, strong) UIButton *playButton;

@property (nonatomic, strong) UIButton *closeButton;

@property (nonatomic, strong) UIImageView *playImgView;

@end

@implementation HYAudioSuspensionView

- (void)dealloc 
{
    CLog(@"dealloc -- %@",self.class);
}

static HYAudioSuspensionView *sharedObj = nil;

+ (HYAudioSuspensionView *)sharedInstance 
{
    @synchronized (self) {
        if (sharedObj == nil) {
            sharedObj = [[self alloc] init];
        }
    }
    return sharedObj;
}

- (void)layoutSubviews 
{
    [super layoutSubviews];
    [self bringSubviewToFront:self.cView];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        
        UIView *cView = [UIView new];
        self.cView = cView;
        [self addSubview:cView];
        [cView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
        
        CGFloat gap = Border_Gap;
        UIView *contentView = [UIView new];
        [cView addSubview:contentView];
        [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.mas_equalTo(gap);
            make.bottom.right.mas_equalTo(-gap);
        }];
        self.contentView = contentView;
        contentView.backgroundColor = [CommUtls dynamicColorWithLightModeHex:@"#F5F5F5" darkModeHex:@"#30343A"];
        contentView.layer.cornerRadius = 22.0;
        contentView.layer.shadowColor = [UIColor blackColor].CGColor;
        contentView.layer.shadowOpacity = 0.15f;//不透明度
        contentView.layer.shadowOffset = CGSizeMake(0, 0);//偏移距离
        
        NSString *imagePath = [[NSBundle mainBundle]pathForResource:@"playing" ofType:@".gif"];
        UIImageView *playImgView = [[UIImageView alloc]init];
        playImgView.contentMode = UIViewContentModeScaleAspectFit;
        playImgView.gifPath = imagePath;
        [contentView addSubview:playImgView];
        [playImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15);
            make.centerY.equalTo(contentView).offset(-1);
            make.width.height.mas_equalTo(22);
        }];
        self.playImgView = playImgView;
        
        UIButton *jumpButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [contentView addSubview:jumpButton];
        [jumpButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.bottom.mas_equalTo(0);
            make.width.mas_equalTo(50);
        }];
        @weakify(self);
        [[jumpButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self);
             if (self.audioRoomPlayer){
                 [[CommUtls getCurrentVC].navigationController pushViewController:self.audioRoomPlayer animated:YES];
                    self.hidden = YES;
                    self.audioRoomPlayer = nil;
            }
        }];
        
        UIView *leftLineView = [UIView new];
        [contentView addSubview:leftLineView];
        [leftLineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(jumpButton.mas_right);
            make.centerY.mas_equalTo(0);
            make.width.mas_equalTo(1);
            make.height.mas_equalTo(16);
        }];
        leftLineView.backgroundColor = UIColor.systemGrayColor; //[CommUtls colorWithHexString:@"#eeeeee"];
        
        UIView *rightLineView = [UIView new];
        [contentView addSubview:rightLineView];
        [rightLineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(99);
            make.centerY.mas_equalTo(0);
            make.width.mas_equalTo(1);
            make.height.mas_equalTo(16);
        }];
        rightLineView.backgroundColor = UIColor.systemGrayColor; //[CommUtls colorWithHexString:@"#eeeeee"];
        
        
        self.isKeepBounds = YES;
        self.freeRect = CGRectMake(10, NAVIGATIONBAR_HEIGHT+10, [UIScreen mainScreen].bounds.size.width-20, [UIScreen mainScreen].bounds.size.height-NAVIGATIONBAR_HEIGHT-TABLE_BAR_HEIGHT-20);
        
        [[[[NSNotificationCenter defaultCenter]rac_addObserverForName:UIApplicationDidEnterBackgroundNotification
                                                               object:nil] takeUntil:[self rac_willDeallocSignal]]
         subscribeNext:^(id x) {
             @strongify(self);
             [self saveEndPlayLoc];
         }];
    }
    return self;
}

/**
 保存最后播放位置
 */
- (void)saveEndPlayLoc 
{
    [[NSUserDefaults standardUserDefaults] setValue:NSStringFromCGRect(self.frame) forKey:End_Play_Loc_Key];
}

- (void)loadingNewView 
{
    [self.playButton removeFromSuperview];
    self.playButton = nil;
    [self.closeButton removeFromSuperview];
    self.closeButton = nil;
    
    UIButton *playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.contentView addSubview:playButton];
    [self.contentView sendSubviewToBack:playButton];
    [playButton setImage:[UIImage imageNamed:@"yp_xf_btn_bf.png"] forState:UIControlStateNormal];
    [playButton setImage:[UIImage imageNamed:@"yp_xf_btn_zt.png"] forState:UIControlStateSelected];
    [playButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(50);
        make.left.mas_equalTo(50);
    }];
    self.playButton = playButton;
    
    UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.contentView addSubview:closeButton];
    [self.contentView sendSubviewToBack:closeButton];
    [closeButton setImage:[UIImage imageNamed:@"yp_xf_btn_closed.png"] forState:UIControlStateNormal];
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(40);
        make.right.mas_equalTo(0);
    }];
    self.closeButton = closeButton;
    @weakify(self);
    [RACObserve(closeButton, hidden) subscribeNext:^(id x) {
        @strongify(self);
        CGFloat gap = Border_Gap;
        if (self.frame.origin.y>0) {
            self.frame = CGRectMake(self.frame.origin.x==10?10:([UIScreen mainScreen].bounds.size.width-([x boolValue]?100:140)-10), self.frame.origin.y, ([x boolValue]?100:140)+gap*2, 44+gap*2);
        } else {
            NSString *rectString = [[NSUserDefaults standardUserDefaults] valueForKey:End_Play_Loc_Key];
            if (rectString) {
                CGRect rect = CGRectFromString(rectString);
                if (rect.origin.y>NAVIGATIONBAR_HEIGHT) {
                    self.frame = CGRectMake(rect.origin.x==10?10:([UIScreen mainScreen].bounds.size.width-([x boolValue]?100:140)-10), rect.origin.y, ([x boolValue]?100:140)+gap*2, 44+gap*2);
                } else {
                    self.frame = CGRectMake(10, [UIScreen mainScreen].bounds.size.height-10-64-40-TABLE_BAR_HEIGHT-10, ([x boolValue]?100:140)+gap*2, 44+gap*2);
                }
            } else {
                self.frame = CGRectMake(10, [UIScreen mainScreen].bounds.size.height-10-64-40-TABLE_BAR_HEIGHT-10, ([x boolValue]?100:140)+gap*2, 44+gap*2);
            }
        }
        if (!IsIOS8) {
            self.contentView.superview.frame = self.bounds;
        }
    }];
    [[closeButton rac_signalForControlEvents:UIControlEventTouchUpInside]
     subscribeNext:^(id x) {
         @strongify(self);
         [self close];
         [self saveEndPlayLoc];
     }];
}


+ (void)showPlayer:(HYAudioRoomViewController *)audioPlayer 
{
    [[self sharedInstance] showPlayer:audioPlayer];
}

+ (void)close 
{
    [[self sharedInstance] close];
}

- (void)showPlayer:(HYAudioRoomViewController *)audioPlayer
{
    self.audioRoomPlayer = audioPlayer;
    self.hidden = NO;
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [[UIApplication sharedApplication].keyWindow bringSubviewToFront:self];
    
    [self loadingNewView];
    @weakify(self);
    self.playButton.rac_command = self.audioRoomPlayer.playView.bottomToolBar.playButton.rac_command;
    RAC(self.playButton, selected) = RACObserve(self.audioRoomPlayer.playView.bottomToolBar.playButton, selected);
    RAC(self.playButton, userInteractionEnabled) = RACObserve(self.audioRoomPlayer.playView.bottomToolBar, userInteractionEnabled);
    [RACObserve(self.audioRoomPlayer.playView.playerManager.player, playStauts) subscribeNext:^(id value) {
        @strongify(self);
        if([value integerValue]){
            [self.playImgView startGIF];
        }else{
            [self.playImgView stopGIF];
        }
    }];
}

- (void)close 
{
    //先停止播放，记录听课轨迹
    if (self.audioRoomPlayer){
        [self.audioRoomPlayer removePlayer];
        self.audioRoomPlayer = nil;
    }
    self.hidden = YES;
}

@end
